package com.wxtwxt.ruralmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wxtwxt.ruralmall.cart.feign.ProductFeign;
import com.wxtwxt.ruralmall.cart.interceptor.CartInterceptor;
import com.wxtwxt.ruralmall.cart.service.CartService;
import com.wxtwxt.ruralmall.cart.to.UserInfoTo;
import com.wxtwxt.ruralmall.cart.vo.Cart;
import com.wxtwxt.ruralmall.cart.vo.CartItem;
import com.wxtwxt.ruralmall.cart.vo.SkuEntityVo;
import com.wxtwxt.ruralmall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author Wxt
 * @create 2023-04-24 21:50
 */
@Service
public class CartServiceImpl implements CartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ThreadPoolExecutor executor;
    @Resource
    private ProductFeign productFeign;

    private static final String CART_PREFIX = "ruralmall:cart:";
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> boundHashOps = getBoundHashOps();
        String redisData = (String) getBoundHashOps().get(skuId.toString());
        if(StringUtils.isNotEmpty(redisData)) {
            CartItem cartItem = JSON.parseObject(redisData, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            boundHashOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
            R r = productFeign.info(skuId);
            if (r.getCode() == 0) {
                SkuEntityVo skuInfo = r.getData("skuInfo", new TypeReference<SkuEntityVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId.toString());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setCount(num);
            }
        }, executor);
        CompletableFuture<Void> getSkuAttrFuture = CompletableFuture.runAsync(() -> {
            List<String> skuAttrList = productFeign.getSkuAttrBySkuId(skuId);
            cartItem.setSkuAttr(skuAttrList);
        }, executor);
        CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrFuture).get();
        boundHashOps.put(skuId.toString(), JSON.toJSONString(cartItem));
        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> boundHashOps = getBoundHashOps();
        String data = (String) boundHashOps.get(skuId.toString());
        return JSON.parseObject(data, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if(userInfoTo.getUserId() != null) {
            List<CartItem> cartItemList = getCartItemList(CART_PREFIX + userInfoTo.getUserKey());
            if(cartItemList != null && cartItemList.size() > 0) {
                for (CartItem cartItem : cartItemList) {
                    addToCart(Long.parseLong(cartItem.getSkuId()), cartItem.getCount());
                }
                stringRedisTemplate.delete(CART_PREFIX + userInfoTo.getUserKey());
            }
            List<CartItem> itemList = getCartItemList(CART_PREFIX + userInfoTo.getUserId());
            cart.setItems(itemList);
        }else {
            List<CartItem> cartItemList = getCartItemList(CART_PREFIX + userInfoTo.getUserKey());
            cart.setItems(cartItemList);
        }
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Boolean check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check);
        BoundHashOperations<String, Object, Object> boundHashOps = getBoundHashOps();
        boundHashOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> boundHashOps = getBoundHashOps();
        boundHashOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> boundHashOps = getBoundHashOps();
        boundHashOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCartItemList() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo == null) {
            return null;
        }
        List<CartItem> cartItemList = getCartItemList(CART_PREFIX + userInfoTo.getUserId());
        if(cartItemList != null && cartItemList.size() > 0) {
            return cartItemList.stream().filter(CartItem::getCheck).map((item) -> {
                R result = productFeign.getPriceBySkuId(item.getSkuId());
                String price = (String) result.get("price");
                item.setPrice(new BigDecimal(price));
                return item;
            }).collect(Collectors.toList());
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object> getBoundHashOps() {
        String cartKey;
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    private List<CartItem> getCartItemList(String cartKey) {
        BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = boundHashOps.values();
        if(values != null && values.size() > 0) {
            return values.stream().map((item) -> {
                String json = item.toString();
                return JSON.parseObject(json, CartItem.class);
            }).collect(Collectors.toList());
        }
        return null;
    }
}
